package com.imooc.util;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author Create By Liuqz
 * @date 2018/12/19 10:27
 */
public class ImageUtil {
    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    private static Random random = new Random();

    public static String generateThumbnail(CommonsMultipartFile file, String targetAddr) {
        String realFileName = getRandomFileName();
        String extension = getFileExtension(file);
        makeDirPath(targetAddr);
        String reatliveAddr = targetAddr + realFileName + extension;
        File dest = new File(PathUtil.getImgeBasePath() + reatliveAddr);
        try {
            Thumbnails.of(file.getInputStream()).size(200, 200).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f).outputQuality(0.8).toFile(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reatliveAddr;
    }

    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = PathUtil.getImgeBasePath() + targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }

    private static String getFileExtension(CommonsMultipartFile file) {
        String originalFileName = file.getOriginalFilename();
        return originalFileName.substring(originalFileName.lastIndexOf("."));
    }

    /**
     * 生成随机文件名: 当前时间 + 5位随机数
     * @return
     */
    private static String getRandomFileName() {
        int r = random.nextInt(89999) + 10000;
        String nowTimeStr = sdf.format(new Date());
        return nowTimeStr + r;
    }
}
